<template>
  <el-table :data="data" border>
    <el-table-column prop="name" label="名称" />
    <el-table-column prop="label" label="标签" />
    <el-table-column label="类型">
      <template #default="{ row }">{{ columnTypeOptions[row.type] }}</template>
    </el-table-column>
    <el-table-column prop="length" label="长度" />
    <el-table-column prop="required" label="是否必填">
      <template #default="{ row }">{{ row.required ? '是' : '否' }}</template>
    </el-table-column>
    <el-table-column prop="unique" label="是否唯一">
      <template #default="{ row }">{{ row.unique ? '是' : '否' }}</template>
    </el-table-column>
    <el-table-column label="操作" :width="100">
      <template #header>
        <OperateBar :operates="['add', 'batch-add','batch-edit']" @add="add" @batch-add="batchAdd" @batch-edit="batchEdit" />
      </template>
      <template #default="{ row }">
        <OperateBar :operates="['edit','component', 'remove']" @edit="edit(row.name)" @component="editElement(row.name)" @remove="remove(row.name)" />
      </template>
    </el-table-column>
  </el-table>
</template>

<script lang="ts" setup>
  import { getSeed } from '@/views/seed-dev'
  import { ElTable, ElTableColumn } from 'element-plus'
  import { computed } from 'vue';
  import { ColumnConfiguration } from '@/views/dev-types';
  import { columnTypeOptions } from '@/views/types';
  import { open } from '@/components/Popup';
  import { ColumnBatchCreator, ColumnCreator, ColumnEditor, ColumnElementEditor } from '../../ColumnEditor';
  import { OperateBar } from '../../OperateBar';
import ColumnBatchEditor from './ColumnBatchEditor.vue';

  const props = defineProps<{seedName: string}>()
  const data = computed((): ColumnConfiguration[] => {
    const ret = []
    const columns = getSeed(props.seedName).columns
    if(!columns) return ret

    for(const columnName in columns) {
      const column = columns[columnName]
      ret.push({...column, name: columnName})
    }

    return ret
  })

  function add() {
    open({title: '创建列'}, ColumnCreator, { seedName: props.seedName })
  }

  function batchAdd() {
    open({title: '批量创建列', fullscreen: true}, ColumnBatchCreator, { seedName: props.seedName })
  }

  function edit(columnName: string) {
    open({title: '编辑列'}, ColumnEditor, { seedName: props.seedName, columnName })
  }

  function batchEdit() {
    open({title: '批量编辑列', fullscreen: true}, ColumnBatchEditor, { seedName: props.seedName })
  }

  function editElement(columnName: string) {
    open({title: '编辑列元素', fullscreen: true}, ColumnElementEditor, { seedName: props.seedName, columnName })
  }

  function remove(columnName: string) {
    const seed = getSeed(props.seedName)
    delete seed.columns[columnName]
  }
</script>